<script setup>
import { ref, onMounted } from "vue";
import { userInfoStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useRouter } from "vue-router";
import { loginAPI, getVCodeKey, getVCode, register, sendCode } from "@/apis/user";

const useUserInfoStore = userInfoStore();

// 登录表单数据
const loginForm = ref({
  // username: "heima282",
  // password: "hm#qd@23!",
  username: "",
  password: "",
  vcode: "",
});

// 注册表单数据
const registerForm = ref({
  username: "",
  email: "",
  verificationCode: "",
  phone: "",
  password: "",
  rePassword:"",
  agree: true,
});

// 表单状态
const isLogin = ref(true);

// 验证码相关数据
const captchaKey = ref("");
const captchaImage = ref(null);

// 登录表单验证规则
const loginRules = {
  username: [{ required: true, message: "用户名不能为空" }],
  password: [
    { required: true, message: "密码不能为空" },
    { min: 6, max: 24, message: "密码长度要求6-24个字符" },
  ],
  vcode: [{ required: true, message: "验证码不能为空" }],
};

// 注册表单验证规则
const registerRules = {
  username: [{ required: true, message: "用户名不能为空" }],
  email: [
    { required: true, message: "邮箱不能为空" },
    { type: "email", message: "邮箱格式不正确" },
  ],
  verificationCode: [{ required: true, message: "验证码不能为空" }],
  phone: [
    { required: true, message: "手机号不能为空" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" },
  ],
  password: [
    { required: true, message: "密码不能为空" },
    { min: 6, max: 24, message: "密码长度要求6-24个字符" },
  ],
  rePassword: [
    { required: true, message: '请输入确认密码' },
    /* { validator: (rule, value, callback) => {
      if (value !== registerForm.password) {
        console.log(value !== registerForm.password)
        console.log(registerForm.password)
        callback(new Error('两次密码不一致'))
      }else {
        callback()
      }
    }, trigger: 'blur' } */
  ],
  agree: [
    {
      validator: (rule, val, callback) => {
        return val ? callback() : new Error("请先同意协议");
      },
    },
  ],
};

// 表单引用
const formRef = ref(null);
const registerFormRef = ref(null);

// 路由
const router = useRouter();

// 获取验证码
const getCaptcha = async () => {
  try {
    const keyResponse = await getVCodeKey();
    console.log("keyResponse: ", keyResponse);
    captchaKey.value = keyResponse.data;
    const captchaResponse = await getVCode({ captchaKey: captchaKey.value });
    captchaImage.value = window.URL.createObjectURL(captchaResponse);
  } catch (error) {
  }
};

// 页面加载时获取验证码
onMounted(() => {
  getCaptcha();
});

// 刷新验证码
const refreshCaptcha = async () => {
  await getCaptcha();
};

// 登录功能
const doLogin = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const { username, password, vcode } = loginForm.value;
      try {
        await useUserInfoStore.getUserInfo(
          { captchaKey: captchaKey.value },
          { username, password, vcode }
        );
        if (useUserInfoStore.resData.code === 200) {
          ElMessage({ type: "success", message: "登录成功" });
          router.replace({ path: "/" });
        }
      } catch (error) {
        // ElMessage({ type: "error", message: "登录失败" });
        // 登录失败刷新验证码
        refreshCaptcha();
      }
    }
  });
};

// 注册功能
const doRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await register({
          user: {
            username: registerForm.value.username,
            email: registerForm.value.email,
            passwordHash: registerForm.value.password,
            phone: registerForm.value.phone,
          },
          code: registerForm.value.verificationCode,
        });
        ElMessage({ type: "success", message: "注册成功" });
        router.replace({ path: "/" });
      } catch (error) {
        ElMessage({ type: "error", message: "注册失败" });
      }
    }
  });
};

// 切换表单
const toggleForm = () => {
  isLogin.value = !isLogin.value;
};

// 验证码倒计时
const isCounting = ref(false);
const count = ref(60);

const getVerificationCode = async () => {
  if (isCounting.value) return;

  // 验证邮箱格式
  if (!registerForm.value.email) {
    ElMessage({ type: "error", message: "请输入邮箱" });
    return;
  }

  const res = await sendCode({ email: registerForm.value.email });
  console.log("res: ", res);
  // 模拟发送验证码
  ElMessage({ type: "success", message: "验证码已发送" });
  isCounting.value = true;

  // 倒计时
  const timer = setInterval(() => {
    count.value--;
    if (count.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
      count.value = 60;
    }
  }, 1000);
};

// 跳转页面
const gotoPage = (url) => {
  router.replace(url);
};
</script>

<template>
  <div>
    <header class="login-header">
      <div class="container m-top-20">
        <h1 class="logo" @click="gotoPage('/')">
          <span class="leftText">School</span>
          <span class="rightText">Shop</span>
        </h1>
        <RouterLink class="entry" to="/">
          进入网站首页
          <i class="iconfont icon-angle-right"></i>
          <i class="iconfont icon-angle-right"></i>
        </RouterLink>
      </div>
    </header>
    <section class="login-section">
      <div class="wrapper">
        <nav>
          <a href="javascript:;">{{ isLogin ? "登录" : "注册" }}</a>
        </nav>
        <div class="account-box">
          <div class="form">
            <el-form
              v-if="isLogin"
              label-position="right"
              label-width="80px"
              status-icon
              :model="loginForm"
              :rules="loginRules"
              ref="formRef"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" type="password" />
              </el-form-item>
              <el-form-item label="验证码" prop="vcode">
                <el-input v-model="loginForm.vcode" style="width: 60%" />
                <img
                  :src="captchaImage"
                  alt="验证码"
                  style="
                    width: 30%;
                    height: 40px;
                    margin-left: 10px;
                    vertical-align: middle;
                    cursor: pointer;
                  "
                  @click="refreshCaptcha"
                />
              </el-form-item>
              <el-form-item label-width="22px" prop="agree">
                <el-checkbox size="large" v-model="loginForm.agree">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subBtn" @click="doLogin">点击登录</el-button>
            </el-form>
            <p
              v-if="isLogin"
              style="width: 100%; text-align: center; color: #27ba9b; padding: 10px"
              @click="toggleForm"
            >
              没有账号？去注册
            </p>

            <el-form
              v-if="!isLogin"
              label-position="right"
              label-width="80px"
              status-icon
              :model="registerForm"
              :rules="registerRules"
              ref="registerFormRef"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="registerForm.username" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="registerForm.email" />
              </el-form-item>
              <el-form-item label="验证码" prop="verificationCode">
                <el-input v-model="registerForm.verificationCode">
                  <template #append>
                    <el-button :disabled="isCounting" @click="getVerificationCode">
                      {{ isCounting ? `${count}秒后重试` : "获取验证码" }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="registerForm.phone" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="registerForm.password" type="password" />
              </el-form-item>
              <el-form-item label="确认密码" prop="rePassword">
                <el-input v-model="registerForm.rePassword" type="password" />
              </el-form-item>
              <el-form-item label-width="22px" prop="agree">
                <el-checkbox size="large" v-model="registerForm.agree">
                  我已同意隐私条款和服务条款
                </el-checkbox>
              </el-form-item>
              <el-button size="large" class="subBtn" @click="doRegister"
                >点击注册</el-button
              >
            </el-form>
            <p
              v-if="!isLogin"
              style="width: 100%; text-align: center; color: #27ba9b; padding: 10px"
              @click="toggleForm"
            >
              已有账号？去登录
            </p>
          </div>
        </div>
      </div>
    </section>

    <footer class="login-footer">
      <div class="container">
        <p>
          <a href="javascript:;">关于我们</a>
          <a href="javascript:;">帮助中心</a>
          <a href="javascript:;">售后服务</a>
          <a href="javascript:;">配送与验收</a>
          <a href="javascript:;">商务合作</a>
          <a href="javascript:;">搜索推荐</a>
          <a href="javascript:;">友情链接</a>
        </p>
        <p>CopyRight &copy; SchoolShop</p>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.login-header {
  background: #fff;
  border-bottom: 1px solid #e4e4e4;
  height: 20vh;

  .container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .logo {
    width: 15vw;
    user-select: none;
    cursor: pointer;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      font-size: 32px;
      font-weight: 700;
    }
    .leftText {
      color: #0095ff;
    }
    .rightText {
      color: #ff4800;
    }
  }

  .entry {
    width: 10vw;
    font-size: 16px;

    i {
      font-size: 14px;
      color: $xtxColor;
      letter-spacing: -5px;
    }
  }
}

.login-section {
  background: url("@/assets/images/login-bg.png") no-repeat center / cover;
  height: 60vh;
  display: flex;
  align-items: center;
  position: relative;

  .wrapper {
    width: 380px;
    background: #fff;
    position: absolute;
    left: 55%;
    transform: translate3d(100px, 0, 0);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);

    nav {
      font-size: 14px;
      height: 55px;
      margin-bottom: 20px;
      border-bottom: 1px solid #f5f5f5;
      display: flex;
      padding: 0 40px;
      text-align: right;
      align-items: center;

      a {
        flex: 1;
        line-height: 1;
        display: inline-block;
        font-size: 18px;
        position: relative;
        text-align: center;
        cursor: pointer;
      }
    }
  }
}

.login-footer {
  padding: 30px 0 50px;
  background: #fff;
  height: 20vh;

  p {
    text-align: center;
    color: #999;
    padding-top: 20px;

    a {
      line-height: 1;
      padding: 0 10px;
      color: #999;
      display: inline-block;

      ~ a {
        border-left: 1px solid #ccc;
      }
    }
  }
}

.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: $xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 20px 20px 20px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: $priceColor;
          }

          &.active,
          &:focus {
            border-color: $xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}

.subBtn {
  background: $xtxColor;
  width: 100%;
  color: #fff;
}
</style>
